<template>
  <div class="opti">
    <el-row v-for="(item, i) in list" :key="i" :gutter="20">
      <el-col :span="2">
        <el-input v-model="item.sort"></el-input>
      </el-col>
      <el-col :span="18">
        <el-input v-model="item.test"></el-input>
      </el-col>
      <el-col :span="1">
        <el-button type="danger" @click="deleteOption(i)">删除</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "optioner",
  watch: {
    list: {
      handler(newvalue) {
        // console.log("执行了", newvalue);
        this.$emit("optionvalue", newvalue);
      },
      //使用deep开启深度监听，只要info对象中任何一个属性变化，都会触发‘对象的侦听器’
      deep: true,
    },
  },
  data() {
    return {
      list: [
        { id: 1, sort: "A", test: "" },
        { id: 2, sort: "B", test: "" },
        // { id: 3, sort: "C", option: "" },
        // { id: 4, sort: "D", option: "" },
      ],
    };
  },
  methods: {
    onSubmit() {
      if (this.list.length >= 4) {
        this.$message.success("最后多添加四个");
        return;
      }
      let obj = { id: this.length + 1, sort: "A", test: "" };
      this.list.push(obj);
      this.optionSoring();
    },
    deleteOption(i) {
      if (i == 0) {
        this.$message.success("最后一个选项不能删除了");
        return;
      }
      this.list.splice(i, 1);
      this.optionSoring();
    },
    //选项重新排序
    optionSoring() {
      for (let i = 0; i < this.list.length; i++) {
        this.list[i].id = i + 1;
        switch (i) {
          case 1:
            this.list[i].sort = "A";
            break;
          case 2:
            this.list[i].sort = "B";
            break;
          case 3:
            this.list[i].sort = "C";
            break;
          case 4:
            this.list[i].sort = "D";
            break;
          default:
            break;
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.opti {
  .el-row {
    margin: 0 0 15px 0;
    margin-left: 0 !important;
  }
}
</style>